package com.ssm.security.authorization;


import com.ssm.service.Impl.ResourcesServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by wchen on 2017/7/13.
 */
public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private ResourcesServiceImpl resourcesServiceImpl;

    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

    public MyInvocationSecurityMetadataSource(ResourcesServiceImpl  resourcesServiceImpl) {
        this.resourcesServiceImpl =resourcesServiceImpl;
        loadResourceDefine();
    }

    private void loadResourceDefine() {
        if (resourceMap == null) {
            resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
            resourceMap= resourcesServiceImpl.getAllRolesByResourceURL();
        }
    }

    // According to a URL, Find out permission configuration of this URL.
    //
    //注意：getAttributes在security3.0和3.2.4写法有区别
    //博文地址：https://xbug.lol/899.html

    /**
     * 根据访问的URL，从以加载的资源中一一进行比对是都有相同的URL，注意，如果资源中有/**这样的表达式，
     * 一定要讲将该表达式放在最后否者当前访问的url会被优先匹配到/**，匹配后就会使用/**所需的权限进行授权
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // guess object is a URL.
        FilterInvocation filterInvocation = (FilterInvocation) object;
        Iterator<String> ite = resourceMap.keySet().iterator();
        while (ite.hasNext()) {
            String requestURL = ite.next();
            RequestMatcher requestMatcher = new AntPathRequestMatcher(requestURL);
            if(requestMatcher.matches(filterInvocation.getHttpRequest())) {//支持"/**"与"/abc"这样的匹配
                return resourceMap.get(requestURL);
            }
        }
        return null;
    }

    public boolean supports(Class<?> clazz) {
        return true;
    }

    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

}
